package com.qf.service.impl;

import com.qf.entity.SysUser;
import com.qf.mapper.SysUserMapper;
import com.qf.service.SysUserService;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/8/28
 * @desc
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("用户认证失败");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
        // 生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", authentication.getName());
        // 获取权限对象，用于提取权限数据
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Set<String> authoritySet = new HashSet<>();
        authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        // 将权限数据放入claims,用于存入jwt
        claims.put("perms", authoritySet);
        return jwtUtils.createJwt(claims);
    }


    public void register(SysUser sysUser) {
        // Spring Security 的密码加密器
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder( );
        String encodePwd = passwordEncoder.encode(sysUser.getPassword( ));
        sysUser.setPassword(encodePwd);
        sysUserMapper.register(sysUser);
    }
}
